package com.example.qincetest.utils

import android.app.ActivityManager
import android.content.Context

class MemoryUtils {
    fun getAvailableMemory(context: Context): MemoryInfo {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val memoryInfo = ActivityManager.MemoryInfo()
        activityManager.getMemoryInfo(memoryInfo)

        return MemoryInfo(
            availableMem = memoryInfo.availMem,  // 可用内存
            totalMem = memoryInfo.totalMem,      // 总内存
            lowMemory = memoryInfo.lowMemory,    // 是否处于低内存状态
            threshold = memoryInfo.threshold      // 低内存阈值

        )
    }

    data class MemoryInfo(
        val availableMem: Long,
        val totalMem: Long,
        val lowMemory: Boolean,
        val threshold: Long
    ) {
        // 转换为MB
        fun getAvailableMemoryInMB() = availableMem / (1024 * 1024)
        fun getTotalMemoryInMB() = totalMem / (1024 * 1024)
        fun getThresholdInMB() = threshold / (1024 * 1024)


        // 获取内存使用百分比
        fun getMemoryUsagePercentage() = ((totalMem - availableMem).toFloat() / totalMem * 100).toInt()
    }
}